import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { message } from 'ant-design-vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { title: '登录' },
    },
    {
      path: '/',
      component: () => import('@/layouts/FrontendLayout.vue'),
      children: [
        {
          path: '',
          name: 'Home',
          component: () => import('@/views/frontend/Home.vue'),
          meta: { title: '首页' },
        },
        {
          path: 'code/:id',
          name: 'CodeDetail',
          component: () => import('@/views/frontend/CodeDetail.vue'),
          meta: { title: '代码详情' },
        },
      ],
    },
    {
      path: '/admin',
      component: () => import('@/layouts/AdminLayout.vue'),
      meta: { requiresAuth: true, requiresAdmin: true },
      children: [
        {
          path: '',
          redirect: '/admin/user',
        },
        {
          path: 'user',
          name: 'AdminUser',
          component: () => import('@/views/admin/UserManage.vue'),
          meta: { title: '用户管理', requiresAuth: true, requiresAdmin: true },
        },
        {
          path: 'code',
          name: 'AdminCode',
          component: () => import('@/views/admin/CodeManage.vue'),
          meta: { title: '代码管理', requiresAuth: true, requiresAdmin: true },
        },
        {
          path: 'tag',
          name: 'AdminTag',
          component: () => import('@/views/admin/TagManage.vue'),
          meta: { title: '标签管理', requiresAuth: true, requiresAdmin: true },
        },
      ],
    },
  ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - Code Share`
  }

  // 如果是登录页，直接放行
  if (to.path === '/login') {
    next()
    return
  }

  // 如果需要认证
  if (to.meta.requiresAuth) {
    // 如果未登录，尝试从后端 session 获取用户信息
    if (!userStore.isLogin) {
      try {
        await userStore.fetchUserInfo()
      } catch (error) {
        // 获取失败说明未登录或 session 已过期
        message.error('请先登录')
        next('/login')
        return
      }
    }

    // 如果需要管理员权限
    if (to.meta.requiresAdmin && !userStore.isAdmin()) {
      message.error('没有权限访问')
      next('/')
      return
    }
  }

  next()
})

export default router
